package org.dormi.learn.completablefuture;

import java.util.concurrent.*;

/**
 * CompletableFuture | thenApply vs thenCompose
 * thenApply vs thenCompose
 * 可以看出 thenApply 都是在一个线程中执行的
 *
 * @author : dormi330
 * @since : 22/04/18
 */
public class CompletableFutureDemo05 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("x1 " + Thread.currentThread().getName());
            timeConsuming(3000);
            return 30;
        }, executorService)
            .thenApply(money -> {
                System.out.println("x2 " + Thread.currentThread().getName());
                Integer point = money < 50 ? 1 : 2;
                return point;
            })
            .thenApply(point -> {
                System.out.println("x3 " + Thread.currentThread().getName());
                Integer pointPlus = point + 1;
                return pointPlus;
            })
            .thenApply(point -> {
                System.out.println("x4 " + Thread.currentThread().getName());
                Integer pointPlus = point + 1;
                return pointPlus;
            })
            .thenApply(point -> {
                System.out.println("x5 " + Thread.currentThread().getName());
                Integer pointPlus = point + 1;
                return pointPlus;
            });

        try {
            Integer result = future.get(5, TimeUnit.SECONDS);
            System.out.println("result= " + result);//result=1
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

        executorService.shutdown();
    }
    /*
x1 pool-1-thread-1
x2 pool-1-thread-1
x3 pool-1-thread-1
x4 pool-1-thread-1
x5 pool-1-thread-1
result= 4
    */

    /** 模拟耗时处理 */
    private static void timeConsuming(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
